﻿//==============================================================================================
//Author: Uncle Song
//Create Date: 2022-07-22
//Description: 网络通信
//----------------------------------------------------------------------------------------------
//Alter History:
//              2010-08-03  add Codes.
//============================================================================================== 
using System;
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

namespace FrameWorkSong
{
    public class HttpRequest : Singleton<HttpRequest>
    {
        public float Progree = 0;
        /// <summary>
        /// 读取图片
        /// </summary>
        /// <param name="url"></param>
        /// <param name="getImg">接受图片的方法</param>
        public void WebGetImg(string url, Action<Texture2D> getImg)
        {
            StartCoroutine(GetRequestImg(url, getImg));
        }
        IEnumerator GetRequestImg(string url, Action<Texture2D> getImg)
        {
            using (var webRequest = UnityWebRequestTexture.GetTexture(url))
            {
                yield return webRequest.SendWebRequest();
               // if (webRequest.isNetworkError || webRequest.isHttpError)
                if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
                {
                    //发送错误
                    Debug.Log(webRequest.error);
                    getImg(null);
                }
                else
                {
                    //发送成功
                    Texture2D Img = DownloadHandlerTexture.GetContent(webRequest);
                    getImg(Img);
                }
            }
        }

        /// <summary>
        /// get查询消息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="getInfo">接收信息的方法</param>
        public void webGet(string url, Action<string> getInfo)
        {
            StartCoroutine(GetRequest(url, getInfo));
        }
        IEnumerator GetRequest(string url, Action<string> getInfo)
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
                yield return webRequest.SendWebRequest();

                // if (webRequest.isNetworkError || webRequest.isHttpError)
                if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
                {
                    //发送错误
                    Debug.LogError(webRequest.error);
                    getInfo("error");
                }
                else
                {
                    //发送成功
                    string str = webRequest.downloadHandler.text;
                    getInfo(str);
                }
            }
        }
        /// <summary>
        /// post增加消息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonString">传入的json数据</param>
        /// <param name="getInfo">接收信息的方法</param>
        public void webPost(string url, string jsonString, Action<string> getInfo)
        {
            StartCoroutine(PostRequest(url, jsonString, getInfo));
        }
        IEnumerator PostRequest(string url, string jsonString, Action<string> getInfo)
        {
            using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
            {
                byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
                webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
                webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
                webRequest.SetRequestHeader("content-type", "application/json");
                yield return webRequest.SendWebRequest();
                // if (webRequest.isNetworkError || webRequest.isHttpError)
                if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
                {
                    //发送错误
                    getInfo("error");
                    Debug.LogError(webRequest.error);
                }
                else
                {
                    //发送成功
                    string str = webRequest.downloadHandler.text;
                    getInfo(str);
                }
            }
        }
        /// <summary>
        /// put修改消息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonString"></param>
        /// <param name="getInfo">接收信息的方法</param>
        public void webPut(string url, string jsonString, Action<string> getInfo)
        {
            StartCoroutine(PutRequest(url, jsonString, getInfo));
        }
        IEnumerator PutRequest(string url, string jsonString, Action<string> getInfo)
        {
            using (UnityWebRequest webRequest = new UnityWebRequest(url, "PUT"))
            {
                byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
                webRequest.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
                webRequest.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
                webRequest.SetRequestHeader("content-type", "application/json");
                yield return webRequest.SendWebRequest();
                // if (webRequest.isNetworkError || webRequest.isHttpError)
                if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
                {
                    //发送错误
                    getInfo("error");
                    Debug.LogError(webRequest.error);
                }
                else
                {
                    //发送成功
                    string str = webRequest.downloadHandler.text;
                    getInfo(str);
                }
            }
        }
        /// <summary>
        /// webDelete删除消息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="getInfo">接收信息的方法</param>
        public void webDelete(string url, Action<string> getInfo = null)
        {
            StartCoroutine(DeleteRequest(url, getInfo));
        }
        IEnumerator DeleteRequest(string url, Action<string> getInfo)
        {
            using (UnityWebRequest webRequest = new UnityWebRequest(url, "DELETE"))
            {
                yield return webRequest.SendWebRequest();
               // if (webRequest.isNetworkError || webRequest.isHttpError)
                if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
                {
                    if (getInfo != null)
                    {
                        //发送错误
                        getInfo("error");
                    }

                    Debug.LogError(webRequest.error);
                }
                else
                {
                    if (getInfo != null)
                    {
                        //发送成功
                        getInfo("succeed");
                    }

                }
            }
        }

        public void DownloadAssetBundle(string url, Action<AssetBundle> getAssetBundle)
        {
            StartCoroutine(DownloadRequestAssetBundle(url, getAssetBundle));
        }
        IEnumerator DownloadRequestAssetBundle(string url, Action<AssetBundle> getAssetBundle)
        {
            using (var webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url))
            {
                webRequest.SendWebRequest();
                 //if (webRequest.isNetworkError || webRequest.isHttpError)
               if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
                {
                    //发送错误
                    Debug.LogError(webRequest.error);
                }
                else
                {
                    while (!webRequest.isDone)
                    {
                        Progree = webRequest.downloadProgress * 100f;
                        yield return new WaitForSeconds(0.01f);
                    }
                    if (webRequest.isDone)
                    {
                        Progree = 0;
                        getAssetBundle(DownloadHandlerAssetBundle.GetContent(webRequest));
                    }
                }
            }
        }
        /// <summary>
        /// 下载资源
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="getAsset">返回资源</param>
        /// <param name="getProgree">返回进度</param>
        public void DownloadData(string url, Action<Byte[]> getAsset, Action<float> getProgree = null)
        {
            Progree = 0;
            StartCoroutine(DownloadRequestData(url, getAsset, getProgree));
        }
        IEnumerator DownloadRequestData(string url, Action<Byte[]> getAsset, Action<float> getProgree = null)
        {
            using (var webRequest = UnityWebRequest.Get(url))
            {
                webRequest.SendWebRequest();
                //if (webRequest.isNetworkError || webRequest.isHttpError)
                if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
                {

                    Debug.LogError(webRequest.error);
                }
                else
                {
                    while (!webRequest.isDone)
                    {
                        Progree = webRequest.downloadProgress * 100f;
                        if (getProgree != null)
                        {
                            getProgree(Progree);
                        }

                        yield return 0;
                    }
                    if (webRequest.isDone)
                    {
                        Progree = 1;
                        if (getProgree != null)
                        {
                            getProgree(Progree);
                        }
                        getAsset(webRequest.downloadHandler.data);

                    }
                }
            }
        }

        public override void OnBeforeDestroy()
        {

        }
    }
}
